<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <el-option value="transactor" label="下单人" />
          <el-option value="ownerName" label="处理人" />
        </el-select>
        <el-input v-model="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmType">
        <el-select v-model="query.csmType" placeholder="请选择">
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" prop="paymentMethod">
        <el-select v-model="query.paymentMethod" placeholder="请选择">
          <el-option
            v-for="item in paymentMethodMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="下单时间:" prop="transactTime">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="订单状态:" prop="orderStatus">
        <el-select v-model="query.orderStatus" placeholder="请选择">
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态:" prop="payStatus">
        <el-select v-model="query.payStatus" placeholder="请选择">
          <el-option
            v-for="item in payStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型:" prop="orderFlag">
        <el-select v-model="query.orderFlag" placeholder="请选择">
          <el-option
            v-for="item in orderFlagMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="excludeWXnoPay" label-width="0">
        <el-checkbox v-model="query.excludeWXnoPay" @change="checkChange">排除微信未支付</el-checkbox>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-switch
          v-model="autoAudit"
          active-text="自动审核"
        />
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      @fetch="fetchData"
    />
    <csm-location ref="csmLocation" />
    <order-detail ref="orderDetail" :pay-status-map="payStatusMap" :payment-method-map="paymentMethodMap" />
    <vetting-orders ref="vettingorders" :customer-type-map="customerTypeMap" />
  </div>
</template>

<script>
  import { queryMap, queryOrderManageList, wechatOrderByDestroy, queryNodealWechatOrderCount } from '@/api'
  import moment from 'dayjs'
  import CsmLocation from '../../components/CsmLocation'
  import OrderDetail from '../orderManage/components/OrderDetails'
  import VettingOrders from './components/VettingOrders'
  import { payStatusObj } from '@/utils/map'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  export default {
    name: 'wechatOrderManage',
    components: {
      CsmLocation,
      OrderDetail,
      VettingOrders
    },
    data() {
      return {
        actionColWidth: 80,
        autoAudit: false,
        payStatusMap: [],
        orderStatusMap: [],
        customerTypeMap: [],
        paymentMethodMap: [],
        orderFlagMap: [],
        qtype: 'contactPhone',
        txt: '',
        date: [moment().subtract(1, 'day'), moment()],
        query: {
          fromPlat: 2, // 只查微信订单
          csmType: '',
          paymentMethod: '',
          dateType: 'transactTime',
          orderStatus: '',
          excludeWXnoPay: false,
          payStatus: '',
          orderFlag: ''
        },
        wechatOrderCount: 0,
        queryTimer: null,
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData'
      ]),
      column: function() {
        return [
          {
            prop: 'orderCode',
            label: '订单号',
            fixed: 'left',
            render: (h, { row }) => (
              <el-link onClick={() => this.openOrderDetail(row)}>
                {row.orderCode}
              </el-link>
            )
          },
          { label: '下单人', prop: 'transactor' },
          { label: '客户名称', prop: 'csmName' },
          { label: '商品描述', prop: 'goodsDesc', width: 250 },
          { label: '联系电话', prop: 'contactPhone', width: 120 },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 220,
            render: (h, { row }) => (
              <span onClick={() => this.openLocation(row)}>
                {row.lon && (
                  <i
                    class='el-icon-location'
                    style='color: #F56C6C;cursor: pointer;'
                  />
                )}
                {row.csmAddress}
              </span>
            )
          },
          { label: '处理人', prop: 'ownerName' },
          { label: '责任机构', prop: 'orgName', width: 150 },
          {
            label: '下单时间',
            prop: 'transactTime',
            width: 120,
            render: (h, { row }) => (
              <span>
                {row.transactTime &&
                parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
          },
          {
            label: '订单状态',
            prop: 'orderStatus',
            render: (h, { row }) => (
              <span>
                {row.orderStatus &&
                formatColumnMap(
                  this.orderStatusMap,
                  'value',
                  row.orderStatus,
                  'desc'
                )}
              </span>
            )
          },
          {
            prop: 'orderFlag',
            label: '订单类型',
            render: (h, { row }) => (
              <span>
                  {row.orderFlag &&
                  formatColumnMap(
                    this.orderFlagMap,
                    'value',
                    row.orderFlag,
                    'desc'
                  )}
                </span>
            )
          },
          {
            label: '支付状态',
            prop: 'payStatus',
            render: (h, { row }) => (
              <span style={payStatusObj[row.payStatus]}>
                {row.payStatus
                  ? formatColumnMap(
                    this.payStatusMap,
                    'value',
                    row.payStatus,
                    'desc'
                  )
                  : '未支付'}
              </span>
            )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
              <span>
                {row.paymentMethod &&
                formatColumnMap(
                  this.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
              </span>
            )
          },
          { label: '备注', prop: 'remark', width: 150 },
          {
            prop: 'appointmentDt',
            label: '配送时效区间',
            align: 'left',
            width: 150,
            render: (h, { row }) => {
              if (row.appointmentDt && moment(row.appointmentDt).format('YYYYMMDD') < 20170316) {
                return moment(row.appointmentDt).format('YY-MM-DD HH:mm') || ''
              }
              if (!row.appointmentDt && !row.dateTimeSpare1) {
                return ''
              } else {
                let color = '#444'
                let title = '正常'
                if (row.dateTimeSpare1) {
                  if (row.orderStatus >= 1 && row.orderStatus < 7) {
                    const m = moment(row.dateTimeSpare1).valueOf() -
                      new Date().getTime()
                    if (m <= 0) { // 已超时，红色
                      color = '#ff0000'
                      title = '已超时'
                    } else if (m / 1000 / 60 < row.intSpare3) { // 未超时但达到预警时间，黄色
                      color = '#ed912e'
                      title = '已达预警时限'
                    }
                  }
                }
                const day = moment(row.appointmentDt || row.dateTimeSpare1).format('MM-DD    ')
                if (row.appointmentDt && !row.dateTimeSpare1) {
                  const time1 = moment(row.appointmentDt).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time1}之后</span>
                  } else {
                    return <span style={color} title={title}>{day}{time1}之后</span>
                  }
                } else if (!row.appointmentDt && row.dateTimeSpare1) {
                  const time2 = moment(row.dateTimeSpare1).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time2}之前</span>
                  } else {
                    return <span style={color} title={title}>{day}{time2}之后</span>
                  }
                } else {
                  const time1 = moment(row.appointmentDt).format('HH:mm')
                  const time2 = moment(row.dateTimeSpare1).format('HH:mm')
                  if (row.orderStatus === 1) {
                    return <span style={color} title={title}>预约:{day}{time1}~{time2}</span>
                  } else {
                    return <span style={color} title={title}>{day}{time1}~{time2}</span>
                  }
                }
              }
            }
          },
          { label: '客户编号', prop: 'csmCode', width: 100 },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => (
              <span>
                {row.csmType &&
                formatColumnMap(
                  this.customerTypeMap,
                  'value',
                  row.csmType,
                  'desc'
                )}
                </span>
            )
          },
          { label: '联系人', prop: 'contact' },
          { label: '商品总数', prop: 'goodsCount', align: 'right' },
          {
            label: '应收金额',
            prop: 'treceivables',
            align: 'right',
            render: (h, { row }) => <span>{ row.fromPlat === 3 ? '/' : row.treceivables }</span>
          },
          {
            label: '实收金额',
            prop: 'taccReceivable',
            align: 'right',
            render: (h, { row }) => <span>{ row.taccReceivable && row.taccReceivable.toFixed(2) }</span>
          },
          {
            label: '需发票',
            align: 'center',
            prop: 'isInvoice',
            render: (h, { row }) => row.isInvoice && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          {
            label: '加急',
            align: 'center',
            prop: 'isUrgent',
            render: (h, { row }) => row.isInvoice && <i class='el-icon-success' style='color: #F56C6C;' />
          },
          { label: '催单次数', prop: 'urgeCount', align: 'right' },
          {
            label: '最后催单时间',
            prop: 'lastUrgeDt',
            width: 150,
            render: (h, { row }) => (
              <span>
                {row.lastUrgeDt &&
                parseTime(row.lastUrgeDt, '{y}-{m}-{d} {h}:{i}')}
              </span>
            )
          },
          {
            label: '签收时间',
            prop: 'signDt',
            width: 150,
            render: (h, { row }) => (
              <span>
                {row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}')}
              </span>
            )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 130,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.orderStatus === 1 && <el-link size='mini' onClick={() => this.vettingorders(row, $index)}>
                    审核并处理
                  </el-link>}
                  {row.orderStatus === 1 && <el-link size='mini' type='danger' onClick={() => this.orderByDestroy(row, $index)}>
                    作废
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap()])
      this.createQueryTimer()
    },
    beforeDestroy() {
      clearInterval(this.queryTimer)
      this.queryTimer = null
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row)
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.transactTime = moment(this.date[0]).format()
          query.transactTimeEnd = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 10) {
          this.$message.warning('选择的时间条件相差不能超过10天')
          return
        }
        const res = await queryOrderManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        if (this.autoAudit) {
          const rows = res.data.rows.find(item => item.orderCode && item.orderStatus !== 1)
          this.tableData.data = rows
        } else {
          this.getNodealWechatOrderCount()
        }
        this.flexColumnWidth()
      },
      // 查询今天未处理的微信订单
      async getNodealWechatOrderCount() {
        const query = {
          ...this._getQuery(this.query)
        }
        if (this.date && this.date.length > 0) {
          query.transactTime = moment(this.date[0]).format()
          query.transactTimeEnd = moment(this.date[1]).format()
        }
        query.orderStatus = 1
        if ((this.corpSettingData.sp1 >> 8 & 0x01) === 0 && (this.corpSettingData.sp1 >> 7 & 0x01) === 1) {
          query.payStatus = 3
        }
        const res = await queryNodealWechatOrderCount({ paramJson: query })
        this.wechatOrderCount = res.data
      },
      createQueryTimer() {
        const _this = this
        this.queryTimer = setInterval(
          function() {
            _this.$refs.lbTable.fetch()
          }, 60000)
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }), mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }), mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }), mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })])
        this.orderStatusMap = res1.data // 订单状态
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data // 支付方式
        const index = res5.data.findIndex(item => item.value === 8)
        this.paymentMethodMap.splice(index, 1) // 支付方式下拉框去掉优惠券
        // 微信商城下单支持微信支付开启 && 微信商城下单支持现金支付关闭
        if ((this.corpSettingData.sp1 >> 7 & 0x01) === 1 && (this.corpSettingData.sp1 >> 8 & 0x01) === 0) {
          this.query.payStatus = 3
        }
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      async vettingorders(row) {
        // 支付方式是微信支付 且 支付状态不是已支付
        const pm = row.paymentMethod
        if (((pm & 2) > 0 || (pm & 64) > 0 || (pm & 128) > 0 || (pm & 512) > 0) && row.payStatus !== 3) {
          this.$message.warning('此订单未支付')
          return
        }
        await this.$refs.vettingorders.open(row)
      },
      orderByDestroy(row, index) {
        this.$confirm(`您确实要作废订单${row.orderCode}吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          wechatOrderByDestroy({ orderCode: row.orderCode })
            .then(() => {
              this.tableData.data.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '作废成功!',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697')
      },
      checkChange(value) {
        this.query.excludeWXnoPay = value
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7) {
          return 'danger-row'
        }
        return ''
      },
      reset() {
        this.$refs.form.resetFields()
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #F99;
}
</style>
